var canvas = document.getElementById( "canvas" );
var context = canvas.getContext( "2d" );

var canvas2 = document.getElementById( "canvas2" );
var context2 = canvas2.getContext( "2d" );

var WIDTH = 1024;
var HEIGHT = 365;
var OFFSET = 48;
var LINE_HEIGHT = 15;
var RADIUS = 15;
var subwayLine;


initMap();
drawMap();

/*Adds all the stations. There should be a global variable that holds an array of Station objects.
This function should be called before drawMap().*/
function initMap()
{
    var myStation0 = new Station("شبرا", "Shubra", "Name is Coptic for small field. Click here for more info.", "images/shubra1.jpg", "images/shubra.jpg", "images/shubra3.jpg", "Shubra has an Islamic and christian flavor as there are so many mosques side by side to the Coptic Orthodox churches in a way that most of the time you can hardly notice to which the minaret belongs. Double click to return.");
    var myStation1 = new Station("كلية الزراعة", "Koleyet Alzeraat", "Agriculture College. Click here for more info.", "images/kuliat.jpg", "images/khu2.jpg", "images/khu3.jpg", "Koleyet Alzeraat Station is primary used by the students of the Agriculture College. Double click to return.");
    var myStation2 = new Station("المظلات", "Elmazallat", "Elmazallat Bridge. Click here for more info.", "images/mazzlat.jpg", "images/maz2.jpg", "images/maz3.jpg", "There are several of important places near this station such as: Elmazallat Bridge, and Nile Corniche. Double click to return.");
    var myStation3 = new Station("الخلفاوي", "El Khalafawi", "El Mamaleek, & Shafeeq Pasha. Click here for more info.", "images/alkhlfawi.png", "images/kh2.png", "images/kh4.png", "This area is the central point for a lot of districts such as: El Mamaleek, Maher, and Shafeeq Pasha. Double click to return.");
    var myStation4 = new Station("سانت تريزا", "St. Teresa", "St. Teresa Church.Click here for more info.", "images/st.jpg", "images/st2.jpg", "images/st3.jpg", "The most important historical markers in this area is St. Teresa Church. In this station, there are some restaurants as: Pizza King and Cook Door. Double click to return. ");
    var myStation5 = new Station("روض الفرج", "Rod El Farag", "Excellent restaurants. Click here for more info", "images/rod.JPG", "images/rod1.jpg", "images/rod2.jpg", "This station holds a lot of good restaurants such as: Masrawi, Al Harameen, Al Dumyati, and Al Umdah. Double click to return.");
    var myStation6 = new Station("المسرة", "Massara", "Tax Office. Click here for more info,", "images/almassara.jpg", "images/msr1.jpg", "images/msr2.jpg", "Use this station to reach the Tax Office. Double click to return.");
    var myStation7 = new Station("الشهداء", "Al Shohadaa", "Trams, metro, & rail. Click here for more info.", "images/alshuhda3.jpg", "images/alshuhada1.jpg", "images/alshuhda2.jpg", "This station is the central point of two metro lines (Massara - El-Atabaa and New El-Marg - Helwan), a tram, and a rail line. Double click to return.");
    
    subwayLine = [myStation0, myStation1, myStation2, myStation3, myStation4, myStation5, myStation6, myStation7];
}
//Draws the entire map by calling its "helper" functions: drawTitle(), drawLine(), drawStations().
function drawMap()
{
    drawBackground();
    drawLine();
    drawStations();
    drawTitle();
}
//Draws the name of the subway line in its native language and English in the upper left-hand corner.
function drawTitle()
{
    context.textAlign = "left";
    context.font = "16pt arial";
    context.fillStyle ="black"; 
    context.fillText("محطة  مترو شبرا- القاهرة , جمهورية مصر العربية", 10, 20 );
    context.fillText("Shubra Metro Line 2 at Cairo, Egypt", 10, 40 );
}
//Draws the subway line.
function drawLine()
{
    var linewidth = WIDTH - OFFSET * 2;
    var startingX = OFFSET;
    var startingY = HEIGHT / 2;

    context.fillStyle = "black";
    context.fillRect( startingX, startingY, linewidth, LINE_HEIGHT);
}
//Draws all the circles along the line with each circle representing a station.
function drawStations()
{
    var startingY = HEIGHT / 2; // calculate the center Y value for each station circle which is dependent on the canvas.height and height of the subway line rectangle
    var width = WIDTH - OFFSET * 2; // calculate the width of the subway line rectangle which you will use to place the circles
    var interval = width / ( subwayLine.length - 1 ); // based on the width of the subway line rectangle, calculate the interval width in pixels between stations

    // assume that subwayLine is a global variable that represents an array of Station objects

    for( var i = 0; i < subwayLine.length; i = i + 1 )
    {
        // draw the circle
        context.beginPath();
        context.arc( OFFSET + i * interval, startingY + RADIUS / 2, RADIUS, 0, 2 * Math.PI, false );
        context.fillStyle = "white";
        context.fill();
        context.strokeStyle = "orange";
        context.stroke();
        
        //colors the circles when clicked/selected to dark blue with a black stroke line.
        if( subwayLine[i].isSelected )
        {
            context.fillStyle = "yellow";
            context.fill();
            context.strokeStyle = "black";
            context.stroke();
        }

        // draw the English and Arabic name
        context.fillStyle = "black";
        context.font = "10pt Arial";
        context.textAlign = "center";

        context.fillText( subwayLine[ i ].getNative(), OFFSET + i * interval, startingY + 40 );
        context.fillText( subwayLine[ i ].getEnglish(), OFFSET + i * interval, startingY + 60 );
    }
}
function drawBackground()
{
    var gradient = context.createLinearGradient( 0, 0, 0, canvas.height );
    gradient.addColorStop( 0, "#FF9933" );
    gradient.addColorStop( .5, "#ccccff" );
    gradient.addColorStop( .75, "white" );
    gradient.addColorStop( 1, "#000022" );
    context.fillStyle = gradient;
    context.fillRect( 0, 0, canvas.width, canvas.height );
}
canvas.onclick = function( evt )
{
    var mouseX = evt.clientX - canvas.clientLeft - canvas.offsetLeft;
    var mouseY = evt.clientY - canvas.clientTop - canvas.offsetTop;

    var width = WIDTH - OFFSET * 2;
    var startingY = HEIGHT / 2;
    var interval = width / ( subwayLine.length - 1 );

    for( var i = 0; i < subwayLine.length; i = i + 1)
    {
        //determine circle's center X
        var centerX = OFFSET + i * interval;
        //determine circle's center Y
        var centerY = HEIGHT / 2;

        if ( ( mouseX - centerX ) * ( mouseX - centerX ) + ( mouseY - centerY ) * ( mouseY - centerY ) < RADIUS * RADIUS )
        {
            currentIndex = [i];
            //sets the circle selected to be true.
            subwayLine[i].isSelected = true;
            document.getElementById( "cairoMusic" ).play();                          
		    animatePreviewInformation();
		    // once we find a matching station, stop the function
            return;
        }
     }
        //function to find the preview picture to call the second canvas.
         if( mouseX >= WIDTH - 300 && mouseY <= 100 )
        {
     		drawInformationCanvas();
        }        
         else
        {
     		//resets the first canvas to all original colors when one does not click on a station.
     		initMap();
     		drawMap();
        }
}
//the function to draw the second canvas that displays more information about each station.
function drawInformationCanvas()
{
    //displays the second canvas since it's not being displayed in css.
    document.getElementById( "canvas2" ).style.display = "inline";
    document.getElementById( "cairoSound" ).play();
    
    //draws the background of the second canvas
    var gradient = context.createLinearGradient( 0, 0, 0, canvas.height );
    gradient.addColorStop( 0, "#FF9933" );
    gradient.addColorStop( .5, "#ccccff" );
    gradient.addColorStop( .75, "white" );
    gradient.addColorStop( 1, "#000022" );
    context.fillStyle = gradient;
    context.fillRect( 0, 0, canvas.width, canvas.height );
    
    context2.shadowColor = "gray";
    context2.shadowBlur = 7;
    context2.shadowOffsetX = 5;
    context2.shadowOffsetY = 5;
    
    context2.fillStyle = "black";
    context2.font = "20pt Arial";
    context2.textAlign = "center";
    
    context2.fillText( subwayLine[ currentIndex ].getNative(), WIDTH / 2, 40 );
    context2.fillText( subwayLine[ currentIndex ].getEnglish(), WIDTH / 2, 70 );
    
    //calls the two pictures that needs to be displayed.
    context2.drawImage( subwayLine[ currentIndex ].getImage1(), 10, 100 );
    context2.drawImage( subwayLine[ currentIndex ].getImage2(), 710, 100 );
    
    //writes the additional information of the station in the middle under the station name.
    // code from: http://www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/
    function wrapText(context, text, x, y, maxWidth, lineHeight) 
    {
        var cars = text.split("\n");

        for (var ii = 0; ii < cars.length; ii++) 
        {
            var line = "";
            var words = cars[ii].split(" ");

            for (var n = 0; n < words.length; n++) 
            {
                var testLine = line + words[n] + " ";
                var metrics = context.measureText(testLine);
                var testWidth = metrics.width;

                if (testWidth > maxWidth) 
                {
                    context.fillText(line, x, y);
                    line = words[n] + " ";
                    y += lineHeight;
                }
                else 
                {
                    line = testLine;
                }
             }
            context.fillText(line, x, y);
            y += lineHeight;
        }
     }
    var maxWidth = 350;
    var lineHeight = 20;
    var x = WIDTH / 2;
    var y = 125;
    var text = subwayLine[ currentIndex ].getFullInfo();
    
    context2.fillStyle = "black";
    context2.font = "12pt Arial";
    
    wrapText( context2, text, x, y, maxWidth, lineHeight );
}
canvas2.onclick = function( evt2 )
{
    //the click function that causes the second canvas to disappear.
    document.getElementById( "canvas2" ).style.display = "none";
    document.getElementById( "cairoMarket" ).play();
}

var previewInformationOpacity = 0;
var previewInformationOffsetY = 0;
var currentIndex = -1;  

function animatePreviewInformation()
{
    context.globalAlpha = 1;
    drawMap();
    
    // this code is just for the image coming down
    context.globalAlpha = previewInformationOpacity;
    // 100 represents the height of the image, 300 represents the width of the image
    context.drawImage( subwayLine[ currentIndex ].getPreviewImage(), WIDTH - 300, previewInformationOffsetY - 100 );

    //writes the native and English names for the stations as well as the preview information.
    context.fillStyle = "Black";
    context.font = "17pt Arial";
    context.textAlign = "center";

    context.fillText( subwayLine[ currentIndex ].getNative(), WIDTH / 2 + 140, previewInformationOffsetY - 70);
    context.fillText( subwayLine[ currentIndex ].getEnglish(), WIDTH / 2 + 140, previewInformationOffsetY - 40);
    context.fillStyle = "black";
    context.font = "10pt Arial";
    context.textAlign = "left";
    context.fillText( subwayLine[ currentIndex ].getInformation(), WIDTH / 2 + 210, previewInformationOffsetY + 15 );
    
    previewInformationOffsetY = previewInformationOffsetY + 2;
    previewInformationOpacity = previewInformationOpacity + .02;

    // keep animating so long as the previewInformationOffsetY is less than or equal to 100, if it is NOT then it's reached its final position
    if( previewInformationOffsetY <= 100 )
    {
           // set the call for the next animation frame
        window.requestAnimationFrame( animatePreviewInformation );
    }
    else
    {
          // reset variables
        previewInformationOpacity = 0;
        previewInformationOffsetY = 0;         
     }
}
//call the request animation from the browser
window.requestAnimationFrame = ( function()
{
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||

     function( callback )
     {
         window.setTimeout( callback, 1000 / 60 );
     };
})(); 